package crud

import (
	"errors"
	"fmt"
	"os"
	"text/template"
	
	"api/system/helper"
)

var Join = helper.Join
var GetRoot = helper.GetRoot

func LoadTemplate(file string) (string, error) {
	fileName := Join(DS, GetRoot(), "system", "template", file)
	fdByte, err := os.ReadFile(fileName)
	if err != nil {
		if errors.Is(err, os.ErrNotExist) {
			return "", fmt.Errorf("文件[%v]不存在", fileName)
		} else if errors.Is(err, os.ErrPermission) {
			return "", fmt.Errorf("文件[%v]没有读取权限", fileName)
		} else {
			return "", err
		}
	}
	
	return string(fdByte), nil
	
}

func TemplateExec(fileName, text string, data map[string]string) error {
	tmpl, err := template.New("test").Parse(text)
	if err != nil {
		return err
	}
	f, err := os.Create(fileName)
	if err != nil {
		return err
	}
	defer f.Close()
	
	err = tmpl.Execute(f, data)
	if err != nil {
		return err
	}
	
	return nil
}
